package com.wsc.springbootmultidevdemo.msg.transaction;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 生产者
 */
public class TxSend {

    private static final String QUEUE_NAME = "TX_hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME,false,false,false,null);

        String msg = "Rabbit MQ transaction test";
        try {
            //开启 channel 事务
            channel.txSelect();
            channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
            System.out.println("sent a message :"+msg);
            //提交事务
            channel.txCommit();
        }catch (Exception e){
            e.printStackTrace();
            //回滚
            channel.txRollback();
        }finally {
            channel.close();
            connection.close();
        }

    }

}
